<?php

namespace app\admin\controller\sales\report;

use app\common\controller\Backend;
use think\Db;

/**
 * 出库管理
 *
 * @icon fa fa-circle-o
 */
class Checkoutgoods extends Backend
{
    
    /**
     * Checkoutgoods模型对象
     * @var \app\common\model\sales\CheckoutGoods
     */
    protected $model = null;
    protected $searchFields = 'id,goods.title,goods.spec';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\sales\CheckoutGoods;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    //库存记录来查 废弃
    public function index4(){

        //设置过滤方法
        if ($this->request->isAjax())
        {

            $filter = json_decode($this->request->get('filter'),true);
            $where = [];

            $start_time = 0;
            $end_time = time();
            $where1 = 'createtime BETWEEN ' . $start_time . ' AND ' . $end_time . '';
            if(!empty($filter)){
                foreach ($filter as $k => $v){
                    if($k == 'createtime'){
                        $time = explode(' - ',$v);
                        $start_time = isset($time[0])?strtotime($time[0]):0;
                        $end_time = isset($time[1])?strtotime($time[1]):time();

                        $where['zax_goods_stock_log.createtime'] = array('between time',[$start_time,$end_time]);
                    }
                    if($k == 'company'){
                        $gids = $this->getgids($v,[$v]);
                        $where['group_id'] = array('in',$gids);
                    }
                }
            }

            $page = input('offset/d',0);
            $pagesize = input('limit/d',0);

            $where['is_cancel'] = 0;//explain
            $where['source'] = array('in',[7,8,9]);

//            $houres = Db::name('storehouse')->select();


            $list = Db::name('goods_stock_log')
                ->field('s.*,g.title,g.number as gnumber,h.name')
                ->alias('s')
                ->join('goods g','s.goods_id = g.id')
                ->join('storehouse h','s.storehouse_id = h.id')
//                ->join('customer c','s.customer_id = c.id')
                ->limit($page,$pagesize)
                ->where($where)
                ->order('id','DESC')
                ->select();
//            foreach ($list as $k=> $v){
//                if($v['enter_num'] == 0){
//                    $list[$k]['goods_num'] = -$v['enter_num'];
//                }
//                if($v['out_num'] == 0){
//                    $list[$k]['goods_num'] = $v['out_num'];
//                }
//            }
            foreach ($list as $k=> $v){
                switch ($v['source']){
                    case 7:
                        $crow = Db::name('sales_checkout_goods')
                            ->where(array('sales_checkout_id'=>$v['type_id'],'goods_id'=>$v['goods_id']))
                            ->find();

                        break;
                    case 8://销售换货单
                        $crow = Db::name('sales_change_goods')
                            ->where(array('sales_change_id'=>$v['type_id'],'goods_id'=>$v['goods_id']))
                            ->find();
                        if($crow['goods_type'] == 1){
                            $crow['goods_num'] = -$crow['goods_num'];
                            $crow['sfhj'] = -$crow['sfhj'];
                        }
                        break;
                    case 9:
                        $crow = Db::name('sales_retreat_goods')
                            ->where(array('sales_retreat_id'=>$v['type_id'],'goods_id'=>$v['goods_id']))
                            ->find();
                        $crow['goods_num'] = -$crow['goods_num'];
                        $crow['sfhj'] = -$crow['sfhj'];
                        break;
                }
                $list[$k]['goods_num'] = $crow['goods_num'];
                $list[$k]['tax'] = $crow['tax'];
                $list[$k]['sfhj'] = $crow['sfhj'];
                $list[$k]['sale_price'] = $crow['sale_price'];
                $list[$k]['costPrice'] = $crow['costPrice'];
                $list[$k]['costmoney'] = bcmul($crow['costPrice'],$crow['goods_num'],2);
                $list[$k]['sale_money'] = $crow['sale_price']*$crow['goods_num'];
                $list[$k]['taxmoney'] = round($crow['sale_price']*$crow['goods_num']['sale_money']*$crow['tax']/100,2);
                $list[$k]['maoli'] = bcsub($crow['sale_price'],$crow['costPrice'],2);
                if($crow['costPrice']>0){
                    if($crow['sale_price'] == '0.00'){
                        $list[$k]['maolil'] = 0;
                    }else{
                        $list[$k]['maolil'] = round(($crow['sale_price']-$crow['costPrice'])/$crow['sale_price'],2)*100 .'%';
                    }
                }else{
                    $list[$k]['maolil'] = 0;
                }
            }


            $total = Db::name('goods_stock_log')
                ->field('s.*,g.title,g.number as gnumber')
                ->alias('s')
                ->join('goods g','s.goods_id = g.id')
                ->where($where)
                ->count();



            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

    public function index6(){
        //设置过滤方法
        if ($this->request->isAjax())
        {
            $filter = json_decode($this->request->get('filter'),true);
            $where = [];
            $start_time = 0;
            $end_time = time();
            $where['sg.createtime'] = array('between time',[$start_time,$end_time]);
            $type = 1;
            if(!empty($filter)){
                foreach ($filter as $k => $v){
                    if($k == 'createtime'){
                        $time = explode(' - ',$v);
                        $start_time = isset($time[0])?strtotime($time[0]):0;
                        $end_time = isset($time[1])?strtotime($time[1]):time();
                        $where['sg.createtime'] = array('between time',[$start_time,$end_time]);
                    }
                    if($k == 'company'){
                        $gids = $this->getgids($v,[$v]);
                        $where['sg.group_id'] = array('in',$gids);
                    }
                    if($k == 'type'){
                        $type = $v;
                    }
                }
            }
            $page = input('offset/d',0);
            $pagesize = input('limit/d',0);
            switch ($type){
                case 1://出库单
                    $list = Db::name('sales_checkout_goods')
                                ->alias('sg')
                                ->join('sales_checkout c','sg.sales_checkout_id = c.id')
                                ->join('storehouse s','sg.storehouse_id = s.id')
                                ->join('goods g','sg.goods_id = g.id')
                                ->limit($page,$pagesize)
                                ->where($where)
                                ->select();
                    $total = Db::name('sales_checkout_goods')
                        ->alias('sg')
                        ->join('sales_checkout c','sg.sales_checkout_id = c.id')
                        ->join('storehouse s','sg.storehouse_id = s.id')
                        ->join('goods g','sg.goods_id = g.id')
                        ->where($where)
                        ->count();
                    break;
                case 2://直发

                    break;
                case 3://换

                    break;
                case 4://退

                    break;
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        if ($this->request->isAjax())
        {

            $filter = json_decode($this->request->get('filter'),true);
            $where = [];

            $start_time = 0;
            $end_time = time();
            $where1 = 'createtime BETWEEN ' . $start_time . ' AND ' . $end_time . '';
            if(!empty($filter)){
                foreach ($filter as $k => $v){
                    if($k == 'createtime'){
                        $time = explode(' - ',$v);
                        $start_time = isset($time[0])?strtotime($time[0]):0;
                        $end_time = isset($time[1])?strtotime($time[1]):time();

                        $where['createtime'] = array('between time',[$start_time,$end_time]);
                        $where1 = 'createtime BETWEEN ' . $start_time . ' AND ' . $end_time . '';
                    }
                    if($k == 'company'){//部门
                        $gids = $this->getgids($v,[$v]);
                        $where['group_id'] = array('in',$gids);
                        $where1  .=' AND group_id IN ('.implode(',',$gids).')';
                    }
                }
            }

//            Db::name('sales_checkout')->where($where)->select();
//            dump(Db::getLastSql());
////
//            dump($where1);
//            exit;
            $page = input('offset/d',0);
            $pagesize = input('limit/d',0);

            $field = 'id,goods_id,createtime,storehouse_id,operator,company,sales_checkout_id,goods_type,goods_num,sfhj,ht_price,costPrice,tax,sale_price,number_type,customer_id,sales_slip_id';
            $field1 = 'id,goods_id,createtime,storehouse_id,operator,company,sales_retreat_id,goods_type,goods_num,sfhj,ht_price,costPrice,tax,sale_price,number_type,customer_id,sales_slip_id';
            $field2 = 'id,goods_id,createtime,storehouse_id,operator,company,sales_change_id,goods_type,goods_num,sfhj,ht_price,costPrice,tax,sale_price,number_type,customer_id,sales_slip_id';
            $field3 = 'id,goods_id,createtime,storehouse_id,operator,company,factory_sales_id,goods_type,goods_num,sfhj,ht_price,unit_price,tax,sale_price,number_type,customer_id,sales_slip_id';
//            $where1 = $where;
            $where2 = $where1;
            $where['status'] = array('>',0);//explain
            $where1.=' AND status > 0';   //['status'] = array('<',4);
            $where2.=' AND status > 0';   //['status'] = array('<',4);
//            $where3.=' AND status > 0';   //['status'] = array('<',4);
//            $where2['status'] = array('<',7);
            $list =Db::field($field)
                ->table('zax_sales_checkout_goods')
//                ->union('SELECT ' . $field1 . ' FROM zax_factory_sales where '.$where1.'', true)
                ->union('SELECT ' . $field1 . ' FROM zax_sales_retreat_goods where '.$where1.'', true)
                ->union('SELECT ' . $field2 . ' FROM zax_sales_change_goods where '.$where2.'', true)
                ->union('SELECT ' . $field3 . ' FROM zax_factory_sales_goods where '.$where2.'', true)
                ->limit($page,$pagesize)
                ->where($where)
                ->order('createtime', 'DESC')
                ->select();


            $total1 = Db::name('sales_checkout_goods')->where($where)->count();
            $newwhere1= $where;
            $newwhere1['status']= array('>',0);
            $total2 = Db::name('sales_retreat_goods')->where($newwhere1)->count();
            $newwhere2= $where;
            $newwhere2['status']= array('>',0);
            $total3 = Db::name('sales_change_goods')->where($newwhere2)->count();
            $total4 = Db::name('factory_sales_goods')->where($newwhere2)->count();
            $total = $total1+$total2+$total3+$total4;

            $outids = [];
            $retreatids = [];
            $changeids = [];
            $factoryids = [];
            $customer_id = [];
            $goods_ids = [];
            $sales_ids = [];
            foreach ($list as &$v){
                $customer_id[] = $v['customer_id'];
                $goods_ids[] = $v['goods_id'];
                $sales_ids[] = $v['sales_slip_id'];
                if($v['goods_type'] == 1){
                    $v['goods_num'] = 0-$v['goods_num'];
                    $v['sfhj'] = 0-$v['sfhj'];
                }
                switch ($v['number_type']){
                    case 7://出库单
                        $outids[] = $v['sales_checkout_id'];
                        break;
                    case 9://退货单
                        $retreatids[] = $v['sales_checkout_id'];
                        break;
                    case 8://换货单
                        $changeids[] = $v['sales_checkout_id'];
                        break;
                    case 12://厂家直发
                        $factoryids[] = $v['sales_checkout_id'];
                        break;
                }
            }
            if(!empty($sales_ids)){
                $sales_ids = array_unique($sales_ids);
            }
            $saless = Db::name('sales_slip')->where(array('id'=>array('in',$sales_ids)))->select();

            $outs = Db::name('sales_checkout')->where(array('id'=>array('in',$outids)))->select();

            $retreats = Db::name('sales_retreat')->where(array('id'=>array('in',$retreatids)))->select();
            $changes = Db::name('sales_change')->where(array('id'=>array('in',$changeids)))->select();

            $factorys = Db::name('factory_sales')->where(array('id'=>array('in',$factoryids)))->select();
            $customers = Db::name('customer')->where(array('id'=>array('in',$customer_id)))->select();
            $goodss= Db::name('goods')->where(array('id'=>array('in',$goods_ids)))->select();

            $houses = Db::name('storehouse')->select();


//            $outcosts = Db::name('cost')->where(array('source_type'=>7,'status'=>2,'source_id'=>array('in',$outids)))->select();
//            $outfacts = Db::name('cost')->where(array('source_type'=>12,'status'=>2,'source_id'=>array('in',$factoryids)))->select();


//            $income = array(
//              1=>'收入',
//              2=>'支出',
//            );

            $fids = [];
//            $costouts = [];
//            $costfacts = [];



            foreach ($list as &$v){
                $v['unit_allfare'] = 0;
                $v['cost'] = 0;
                $v['cost_type'] = '';
                switch ($v['number_type']){
                    case 7://出库单

                       foreach ($outs as $val){
                           if($val['id'] == $v['sales_checkout_id']){
                               $v['type'] = '销售出库单';
                               $v['number'] =$val['number'];
                               $v['explain'] =$val['explain'];
                               $v['controller'] = 'sales/checkout';
//                               if(!in_array($val['id'],$outis)){
//                                   $v['unit_allfare'] = $val['unit_allfare'];
//                               }
//                               if(!in_array($val['id'],$costouts)){
//                                   foreach ($outcosts as $value){
//                                       if($value['source_id'] == $val['id'] ){
//                                           $costouts[] = $val['id'];
//                                           if(!empty($v['cost'])){
//                                               $v['cost'] .= '+'.$value['cost'];
//                                               $v['cost_type'] .= '+'.$income[$value['is_income']];
//                                           }else{
//                                               $v['cost'] = $value['cost'];
//                                               $v['cost_type'] = $income[$value['is_income']];
//                                           }
//                                       }
//                                   }
//                               }
                           }
                       }
                        break;
                    case 9://退货单
                        foreach ($retreats as $val){
                            if($val['id'] == $v['sales_checkout_id']){
                                $v['type'] = '销售退货单';
                                $v['number'] =$val['number'];
                                $v['explain'] =$val['explain'];
                                $v['controller'] = 'sales/retreat';
                            }
                        }
                        break;
                    case 8://换货单
                        foreach ($changes as $val){
                            if($val['id'] == $v['sales_checkout_id']){
                                $v['type'] = '销售换货单';
                                $v['number'] =$val['number'];
                                $v['explain'] =$val['explain'];
                                $v['controller'] = 'sales/change';
                            }
                        }
                        break;
                    case 12://厂家直发单
                        foreach ($factorys as $val){
                            if($val['id'] == $v['sales_checkout_id']){
                                $v['type'] = '厂家直发单';
                                $v['number'] =$val['number'];
                                $v['explain'] =$val['explain'];
                                $v['controller'] = 'factory/sales';
//                                if(!in_array($val['id'],$fids) && $val['allfare_type'] == 2){
                                if(!in_array($val['id'],$fids)){
                                    $fids[] = $val['id'];
                                    $v['unit_allfare'] = $val['unit_allfare'];
                                }

//                                if(!in_array($val['id'],$costfacts)){
//                                    foreach ($outfacts as $value){
//                                        if($value['source_id'] == $val['id'] ){
//                                            $costfacts[] = $val['id'];
//                                            if(!empty($v['cost'])){
//                                                $v['cost'] .= '+'.$value['cost'];
//                                                $v['cost_type'] .= '+'.$income[$value['is_income']];
//                                            }else{
//                                                $v['cost'] = $value['cost'];
//                                                $v['cost_type'] = $income[$value['is_income']];
//                                            }
//                                        }
//                                    }
//                                }
                            }
                        }
                        break;
                }
                foreach ($houses as $val){
                    if($val['id'] == $v['storehouse_id']){
                        $v['name'] = $val['name'];
                    }
                }
                foreach ($customers as $val){
                    if($val['id'] == $v['customer_id']){
                        $v['ccompany'] = $val['company'];
                    }
                }
                foreach ($goodss as $val){
                    if($val['id'] == $v['goods_id']){
                        $v['title'] = $val['title'];
                        $v['specs'] = $val['specs'];
                        $v['gnumber'] = $val['number'];
                    }
                }
                foreach ($saless as $val){
                    if($val['id'] == $v['sales_slip_id']){
                        $v['source_admin'] = $val['operator'];
                    }
                }

                $v['sale_money'] =  round($v['sale_price']*$v['goods_num'],2);
                $v['costmoney'] = bcmul($v['costPrice'],$v['goods_num'],2);
                $v['ht_money'] = round($v['ht_price']*$v['goods_num'],2);
                $v['taxmoney'] = round($v['sale_money']*$v['tax']/100,2);
                $v['maoli'] = bcmul(bcsub($v['sale_price'],$v['costPrice'],2),$v['goods_num'],2);
//                dump($v['maoli']);
                if($v['costPrice']>0){
                    if($v['sale_price'] == '0.00'){
                        $v['maolil'] = 0;
                    }else{
                        $v['maolil'] = round(($v['sale_price']-$v['costPrice'])/$v['sale_price'],2)*100 .'%';
                    }
//                    $v['maolil'] = round(($v['sale_price']-$v['costPrice'])/$v['costPrice'],2)*100 .'%';

                }else{
                    $v['maolil'] = 0;
                }

            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }
    public function getgroup(){
        $state = input('state/d',0);
        switch ($state){
            case 1:
                $groups = Db::name('auth_group')->where(array('pid'=>1))->column('id,name');
                return $groups;
                break;
            case 2:
                $groups  = array(
                  1=>'销售出库单',
                  2=>'厂家直发单',
                  3=>'销售换货单',
                  4=>'销售退货单',
                );
                return $groups;
                break;
        }


    }
    /**
     * 查看  只根据出库单 废弃
     */
    public function index1()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $filter = json_decode($this->request->get('filter'),true);
            $op = json_decode($this->request->get('op'),true);
            $where1 = [];
            if(!empty($filter) && isset($filter['company'])){
                $company = $filter['company'];
                $group = Db::name('auth_group')->where(array('name'=>$company))->find();
                $gids = [];
                if($group){
                    $gids = $this->getgids([$group['id']],[$group['id']]);
                }
                unset($filter['company']);
                unset($op['company']);
                $where1 = array(
                    'zax_sales_checkout_goods.group_id'=>array('in',$gids)
                );
//                dump($where1);
//                exit;

            }
            $this->request->get(["filter"=> json_encode($filter),'op'=>json_encode($op)]);

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['salescheckout','salesslip','storehouse','goods','customer'])
                    ->where($where)
                    ->where($where1)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['salescheckout','salesslip','storehouse','goods','customer'])
                    ->where($where)
                    ->where($where1)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','goods_num','sale_price','tax','remark','status','ht_price','createtime','costPrice','operator','company']);
                $row->visible(['salescheckout']);
				$row->getRelation('salescheckout')->visible(['number','explain','id']);
				$row->visible(['salesslip']);
				$row->getRelation('salesslip')->visible(['number']);
				$row->visible(['storehouse']);
				$row->getRelation('storehouse')->visible(['name']);
                $row->visible(['goods']);
                $row->getRelation('goods')->visible(['title','specs','place_origin','number','unit']);
                $row->visible(['customer']);
                $row->getRelation('customer')->visible(['company','nickname']);
            }
            $list = collection($list)->toArray();

            foreach ($list as &$v){
//                $v['sf_price'] = $v['ht_price']*$v['goods_num'];
                $v['type'] = '销售出库单';
                $v['sale_money'] =  round($v['sale_price']*$v['goods_num'],2);
                $v['costmoney'] = round($v['costPrice']*$v['goods_num'],2);
                $v['ht_money'] = round($v['ht_price']*$v['goods_num'],2);
                $v['taxmoney'] = round($v['sale_money']*$v['tax'],2);
                $v['maoli'] = bcsub($v['sale_price'],$v['costPrice'],2);
//                dump($v['maoli']);
                if($v['costPrice']>0){
                    if($v['sale_price'] == '0.00'){
                        $v['maolil'] = 0;
                    }else{
                        $v['maolil'] = round(($v['sale_price']-$v['costPrice'])/$v['sale_price'],2)*100 .'%';
                    }
//                    $v['maolil'] = round(($v['sale_price']-$v['costPrice'])/$v['costPrice'],2)*100 .'%';

                }else{
                    $v['maolil'] = 0;
                }

            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
}
